Типы данных в Python

1. Числовые

int


In [1]:
x = 5

In [2]:
print x


  File "<ipython-input-2-2d264e11d975>", line 1
    print x
          ^
SyntaxError: Missing parentheses in call to 'print'

In [3]:
print type(x)


  File "<ipython-input-3-ee69df525b82>", line 1
    print type(x)
             ^
SyntaxError: invalid syntax

In [240]:
a = 4 + 5
b = 4 * 5
c = 5 / 4

print a, b, c


9 20 1

In [241]:
print -5 / 4


-2

In [242]:
print -(5 / 4)


-1

long


In [243]:
x = 5 * 1000000 * 1000000 * 1000000 * 1000000 + 1
print x
print type(x)


5000000000000000000000001
<type 'long'>

In [244]:
y = 5
print type(y)
y = x
print type(y)


<type 'int'>
<type 'long'>

float


In [245]:
y = 5.7

In [246]:
print y
print type(y)


5.7
<type 'float'>

In [247]:
a = 4.2 + 5.1
b = 4.2 * 5.1
c = 5.0 / 4.0

print a, b, c


9.3 21.42 1.25

In [248]:
a = 5
b = 4
print float(a) / float(b)


1.25

In [249]:
print 5.0 / 4
print 5 / 4.0


1.25
1.25

In [250]:
print float(a) / b


1.25

bool


In [251]:
a = True
b = False

print a
print type(a)

print b
print type(b)


True
<type 'bool'>
False
<type 'bool'>

In [252]:
print a + b
print a + a
print b + b


1
2
0

In [253]:
print int(a), int(b)


1 0

In [254]:
print True and False
print True and True
print False and False


False
True
False

In [255]:
print True or False
print True or True
print False or False


True
True
False

2. None


In [256]:
z = None
print z
print type(z)


None
<type 'NoneType'>

In [257]:
print int(z)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-257-faf6fd86913f> in <module>()
----> 1 print int(z)

TypeError: int() argument must be a string or a number, not 'NoneType'

3. Строковые

str


In [258]:
x = "abc"
print x
print type(x)


abc
<type 'str'>

In [259]:
a = 'Ivan'
b = "Ivanov"
s = a + " " + b
print s


Ivan Ivanov

In [260]:
print a.upper()
print a.lower()


IVAN
ivan

In [261]:
print len(a)


4

In [262]:
print bool(a)
print bool("")


True
False

In [263]:
print int(a)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-263-5f424ac5bb38> in <module>()
----> 1 print int(a)

ValueError: invalid literal for int() with base 10: 'Ivan'

In [264]:
print a
print a[0]
print a[1]
print a[0:3]


Ivan
I
v
Iva

In [265]:
print a[0:4:2]


Ia

unicode


In [266]:
x = u"abc"
print x
print type(x)


abc
<type 'unicode'>

In [267]:
x = u'Элеонора Михайловна'
print x, type(x)
y = x.encode('utf-8')
print y, type(y)
z = y.decode('utf-8')
print z, type(z)
q = y.decode('cp1251')
print q, type(q)


Элеонора Михайловна <type 'unicode'>
Элеонора Михайловна <type 'str'>
Элеонора Михайловна <type 'unicode'>
Элеонора Михайловна <type 'unicode'>

In [248]:
1


Out[248]:
1

In [263]:
x = u'Элеонора Михайловна'
print x, type(x)
y = x.encode('utf-8')
print y, type(y)
z = y.decode('utf-8')
print z, type(z)
q = y.decode('cp1251')
print q, type(q)


Элеонора Михайловна <type 'unicode'>
Элеонора Михайловна <type 'str'>
Элеонора Михайловна <type 'unicode'>
Элеонора Михайловна <type 'unicode'>

In [268]:
print str(x)


---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-268-814029ae4c69> in <module>()
----> 1 print str(x)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-7: ordinal not in range(128)

In [269]:
print y[1:]
print len(y), type(y)
print len(x), type(x)


�леонора Михайловна
37 <type 'str'>
19 <type 'unicode'>

In [270]:
y = u'Иван Иванович'.encode('utf-8')
print y.decode('utf-8')


Иван Иванович

In [271]:
print y.decode('cp1251')


---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-271-007dbaadc60e> in <module>()
----> 1 print y.decode('cp1251')

/Users/xead/anaconda/lib/python2.7/encodings/cp1251.pyc in decode(self, input, errors)
     13 
     14     def decode(self,input,errors='strict'):
---> 15         return codecs.charmap_decode(input,errors,decoding_table)
     16 
     17 class IncrementalEncoder(codecs.IncrementalEncoder):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1: character maps to <undefined>

In [273]:
splitted_line = "Ivanov Ivan Ivanovich".split(' ')
print splitted_line


['Ivanov', 'Ivan', 'Ivanovich']

In [274]:
print type(splitted_line)


<type 'list'>

In [275]:
print "Иванов Иван Иванович".split(" ")


['\xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbe\xd0\xb2', '\xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd', '\xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbe\xd0\xb2\xd0\xb8\xd1\x87']

In [277]:
print "\x98"



In [278]:
print u"Иванов Иван Иванович".split(" ")


[u'\u0418\u0432\u0430\u043d\u043e\u0432', u'\u0418\u0432\u0430\u043d', u'\u0418\u0432\u0430\u043d\u043e\u0432\u0438\u0447']

3. Массивы

list


In [279]:
saled_goods_count = [33450, 34010, 33990, 33200]
print saled_goods_count
print type(saled_goods_count)


[33450, 34010, 33990, 33200]
<type 'list'>

In [280]:
income = [u'Высокий', u'Средний', u'Высокий']
names = [u'Элеонора Михайловна', u'Иван Иванович', u'Михаил Абрамович']

print income
print names


[u'\u0412\u044b\u0441\u043e\u043a\u0438\u0439', u'\u0421\u0440\u0435\u0434\u043d\u0438\u0439', u'\u0412\u044b\u0441\u043e\u043a\u0438\u0439']
[u'\u042d\u043b\u0435\u043e\u043d\u043e\u0440\u0430 \u041c\u0438\u0445\u0430\u0439\u043b\u043e\u0432\u043d\u0430', u'\u0418\u0432\u0430\u043d \u0418\u0432\u0430\u043d\u043e\u0432\u0438\u0447', u'\u041c\u0438\u0445\u0430\u0438\u043b \u0410\u0431\u0440\u0430\u043c\u043e\u0432\u0438\u0447']

In [282]:
print "---".join(income)


Высокий---Средний---Высокий

In [283]:
features = ['Ivan Ivanovich', 'Medium', 500000, 12, True]
print features


['Ivan Ivanovich', 'Medium', 500000, 12, True]

In [284]:
print features[0]
print features[1]
print features[3]


Ivan Ivanovich
Medium
12

In [285]:
print features[0:5]


['Ivan Ivanovich', 'Medium', 500000, 12, True]

In [286]:
print features[:5]


['Ivan Ivanovich', 'Medium', 500000, 12, True]

In [287]:
print features[1:]


['Medium', 500000, 12, True]

In [288]:
print features[2:5]


[500000, 12, True]

In [289]:
print features[:-1]


['Ivan Ivanovich', 'Medium', 500000, 12]

In [290]:
features.append('One more element in list')
print features


['Ivan Ivanovich', 'Medium', 500000, 12, True, 'One more element in list']

In [291]:
del features[-2]

In [292]:
print features


['Ivan Ivanovich', 'Medium', 500000, 12, 'One more element in list']

tuple


In [293]:
features_tuple = ('Ivan Ivanovich', 'Medium', 500000, 12, True)
print type(features_tuple)


<type 'tuple'>

In [294]:
features_tuple[2:5]


Out[294]:
(500000, 12, True)

In [295]:
features_tuple.append('one more element')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-295-ea16a6b56b87> in <module>()
----> 1 features_tuple.append('one more element')

AttributeError: 'tuple' object has no attribute 'append'

4. Множества и словари

set


In [296]:
names = {'Ivan', 'Petr', 'Konstantin'}

In [297]:
print type(names)


<type 'set'>

In [298]:
print 'Ivan' in names


True

In [299]:
print 'Mikhail' in names


False

In [300]:
names.add('Mikhail')
print names


set(['Ivan', 'Mikhail', 'Konstantin', 'Petr'])

In [301]:
names.add('Mikhail')
print names


set(['Ivan', 'Mikhail', 'Konstantin', 'Petr'])

In [302]:
names.remove('Mikhail')
print names


set(['Ivan', 'Konstantin', 'Petr'])

In [303]:
names.add(['Vladimir', 'Vladimirovich'])


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-303-4a104b0fb39e> in <module>()
----> 1 names.add(['Vladimir', 'Vladimirovich'])

TypeError: unhashable type: 'list'

In [304]:
names.add(('Vladimir', 'Vladimirovich'))
print names


set(['Ivan', ('Vladimir', 'Vladimirovich'), 'Konstantin', 'Petr'])

In [305]:
a = range(10000)
b = range(10000)
b = set(b)

In [306]:
print a[:5]
print a[-5:]


[0, 1, 2, 3, 4]
[9995, 9996, 9997, 9998, 9999]

In [307]:
%%time
print 9999 in a


True
CPU times: user 675 µs, sys: 70 µs, total: 745 µs
Wall time: 752 µs

In [308]:
%%time
print 9999 in b


True
CPU times: user 49 µs, sys: 9 µs, total: 58 µs
Wall time: 55.1 µs

dict


In [309]:
words_frequencies = dict()
words_frequencies['I'] = 1
words_frequencies['am'] = 1
words_frequencies['I'] += 1

print words_frequencies


{'I': 2, 'am': 1}

In [310]:
print words_frequencies['I']


2

In [311]:
words_frequencies = {'I': 2, 'am': 1}
print words_frequencies


{'I': 2, 'am': 1}

In [312]:
yet_another_dict = {'abc': 3.4, 5: 7.8, u'123': None}
print yet_another_dict


{u'123': None, 'abc': 3.4, 5: 7.8}

In [313]:
yet_another_dict[(1,2,5)] = [4, 5, 7]
print yet_another_dict


{u'123': None, 'abc': 3.4, 5: 7.8, (1, 2, 5): [4, 5, 7]}

In [314]:
yet_another_dict[[1,2,7]] = [4, 5]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-314-d896033641d2> in <module>()
----> 1 yet_another_dict[[1,2,7]] = [4, 5]

TypeError: unhashable type: 'list'

Где еще можно познакомиться с Python


In [ ]: